package com.just.fun.search;

/**
 * Created by han.yuan
 * 2018/4/9
 * 查找方法
 */
public class CrazySearch {
    public static void main(String[] args){
        int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
        System.out.println(binarySearch(a,11));
    }

    /**
     * 二分查找
     * 元素必须有序
     * 非递归方法
     */
    public static int binarySearch(int[] a,int searchKey){
        int length=a.length;
        int left=0;
        int right=length-1;
        int mid;
        while (left<right){
            mid=(left+right)/2;
            if(searchKey<mid){
                right=mid-1;
            }
            if(searchKey>mid){
                left=mid-1;
            }
            if(searchKey==mid){
               return mid;
            }
        }
        return -1;
    }
}
